const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../../config')
const UserModel = require('../../model')

exports.regUser = (req, res) => {
  const userInfo = req.body
  console.log(userInfo);
  userInfo.password = bcrypt.hashSync(userInfo.password, 10)
  UserModel.Modal.find({ "username": userInfo.username }, (err, result) => {
    if (err) return res.cc(err)
    if (result.length) {
      return res.send({ status: 400, message: '用户名已被占用,请更换其他用户名！' })
    }
    let addUser = UserModel.Modal({
      ...userInfo
    })
    addUser.save((err, result) => {
      res.send({ status: 200, message: '注册成功' })
    })
  })
}

exports.login = (req, res) => {
  const userInfo = req.body
  if (!userInfo.username || !userInfo.password) {
    return res.send({ status: 400, message: '用户名或密码不正确' })
  }
  UserModel.Modal.find({ "username": userInfo.username }).lean().exec((err, result) => {
    if (err) return res.cc(err)
    if (!result.length) {
      return res.cc('登录失败')
    }
    const compareResult = bcrypt.compareSync(userInfo.password, result[0].password)
    if (!compareResult) {
      return res.cc('密码错误')
    }
    const user = { ...result[0], password: '', avatar: '' }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: '1h'
    })
    res.send({
      status: 200,
      message: '登录成功',
      token: `Bearer ${tokenStr}`
    })
  })
}